<?php

namespace app\api\controller;

use app\common\Queue;
use think\facade\Cache;
use think\facade\Queue as QueueFacade;

class TestController extends BaseApiController
{
    public array $notNeedLogin = ['testCreateUser', 'testNotification', 'testDelayQueue', 'status'];
    /**
     * 测试创建用户队列
     */
    public function testCreateUser()
    {
        $userData = [
            'username' => 'test_user_' . uniqid(),
            'password' => '123456',
            'nickname' => 'Test User',
            'email' => 'test@example.com',
            'mobile' => '13800138000',
            'create_time' => time(),
            'update_time' => time()
        ];

        $result = QueueFacade::push('\app\common\Queue@fire',  [
            'type' => 'create_user',
            'data' => $userData
        ]);

        if ($result) {
            return $this->success('任务已加入队列');
        }
        return $this->fail('任务推送失败');
    }

    /**
     * 测试通知队列
     */
    public function testNotification()
    {
        $result = QueueFacade::push('\app\common\Queue@fire',  [
            'type' => 'send_notification',
            'data' => [
                'user_id' => 1,
                'message' => '这是一条测试通知',
                'type' => 'test'
            ]
        ]);
        // 自定义list
//        $result = Queue::pushNotification(
//            userId: 1,
//            message: '这是一条测试通知',
//            type: 'test'
//        );

        if ($result) {
            return $this->success('通知任务已加入队列');
        }
        return $this->fail('通知任务推送失败');
    }

    /**
     * 测试延迟队列
     */
    public function testDelayQueue()
    {
        try {
            // 延迟60秒执行的通知
            QueueFacade::later(60, '\app\common\Queue@fire', [
                'type' => 'send_notification',
                'data' => [
                    'user_id' => 1,
                    'message' => '这是一条延迟60秒的通知',
                    'type' => 'delay_test'
                ]
            ]);

            return $this->success('延迟任务已加入队列');
            
        } catch (\Exception $e) {
            return $this->fail('延迟任务推送失败：' . $e->getMessage());
        }
    }

    /**
     * 查看队列状态
     */
    public function status()
    {
        try {
            // 获取失败队列长度
            $queueLength = Cache::llen('default');
            $failedLength = Cache::llen('failed');
//            $redis = app('redis');
//            $redis->connect('localhost',6379);
//            $failedLength = $redis->llen('failed');

            return $this->success('获取成功', [
                'queue_length' => $queueLength,
                'failed_length' => $failedLength
            ]);
            
        } catch (\Exception $e) {
            return $this->fail('获取队列状态失败：' . $e->getMessage());
        }
    }
} 